package user.zc.util;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.function.Consumer;
import java.util.function.Supplier;

@Data
@Accessors(chain = true)
public class R {

    private enum Code {
        OK(200, "OK"), FAIL(500, "FAIL");
        private int value;
        private String desc;

        Code(int value, String desc) {
            this.value = value;
            this.desc = desc;
        }
    }

    private int code = Code.OK.value;
    private String msg = "OK";
    private Object data;

    private R(int code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    private R() {

    }

    public Boolean isOk(){
        return this.code==200;
    }

    public static R success(Object data) {
        return create(Code.OK.value, Code.OK.desc, data);
    }

    public static R ok(String msg) {
        return create(Code.OK.value, msg, null);
    }

    public static R ok() {
        return new R();
    }

    public static R failure(String msg) {
        return create(Code.FAIL.value, msg, null);
    }

    public static R create(int code, String msg, Object data) {
        return new R(code, msg, data);
    }

    public R message(String msg) {
        this.msg = msg;
        return this;
    }

    public static <T>  R success(Supplier<T> executor){
        try {
            return success(executor.get());
        } catch (Exception e) {
            e.printStackTrace();
            return R.failure(e.getMessage());
        }
    }
}
